####################################################
# Allnetworkvariables.R
#
# This function computes all the discounted network variables to replicate TableA7 for #the on-line appendix of Ductor, L., Fafchamps, M., Goyal S. and M. van der Leij. Social #Networks and Research Output. The Review of Economics and Statistics.
# 
#   Note: this program is time consuming (more than 3 weeks in a standard PC)         
#                
######################################################


#Obtaining the full sample of all authors (do only once)#

library(igraph)
source("netprodndnp.R")
source("netprod2ndnp.R")
source("getcoauthnetwk.R")
source("analyzenetw.R")

data<-read.csv("networkdatacdt.csv",header=TRUE)
dataqnt<-read.csv("qntdt_fullsample.csv",header=TRUE)

# endyears and length to compute networks
ks <- 1:15

for (k in ks) {

  endyears <- (1970+k-1):1999

  for (endyear in endyears) {

    startyear <- endyear - k+1

    #COMPUTING COAUTHORS' PRODUCTIVITY AND DEGREE
    y <- subset(data,year>=startyear & year<=endyear)
    g <- getnetwork(startyear,endyear, data, y)

    y$auth3[is.na(y$auth3)]<--2  ### Replacing missing author by a number, -2
    y$auth2[is.na(y$auth2)]<--1  ### Replacing missing author by a number, -1

    V(g)$deg <- degree(g)
    V(g)[deg>0]$netprod <- sapply(V(g)[deg>0],netprod,g,y)

    V(g)$auth<-V(g)

    #COMPUTING COAUTHORS' COAUTHORS PRODUCTIVITY
    
    V(g)[deg>0]$netprod2<-sapply(V(g)[deg>0],netprod2,g,y)

    #COMPUTING THE DEGREE OF ORDER 2 
    V(g)$deg2<- neighborhood.size(g, 2) - V(g)$deg - 1


    #COMPUTING THE TOP COAUTHORS DUMMY VARIABLE
    if (endyear >= 1970) {
      qnt1<-subset(dataqnt,qntdt==1 & year==endyear,auth)
      qnt1v<-qnt1$auth
      neiq1v<-V(g)[nei(qnt1v)]
      V(g)[neiq1v]$neiq1fsdt<-1
    }
    else {
      V(g)$neiq1fsdt <- NA }

    d<-data.frame(V(g)$auth,V(g)$deg,V(g)$deg2,V(g)$netprod,V(g)$netprod2,
                     V(g)$neiq1fsdt)

    write.csv(d,file=paste("networkdt", endyear, "_", k, "y.csv", sep=""),na=".")
 }
}